import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus, Inject } from '@nestjs/common'
import { WINSTON_MODULE_PROVIDER } from 'nest-winston'
import { Logger } from 'winston'
import { getInfoFromReq } from '@/util/util'
import { Request } from 'express'

/**
 * 全局异常过滤器
 */
@Catch(HttpException)
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse()
    const request = ctx.getRequest() as Request
    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
    this.logger.error(this.getErrorMsg(exception), {
      status,
      req: getInfoFromReq(request),
    })

    response.status(status).json({
      statusCode: status,
      // path: request.url,
      message: this.getErrorMsg(exception),
    })
  }

  //根据异常类型返回错误消息
  getErrorMsg(exception: HttpException): string {
    if (exception.name === 'UnauthorizedException') {
      return '登陆状态已失效'
    }
    if (exception.name === 'QueryFailedError' || exception.name === 'BadRequestException') {
      return '请求参数错误'
    }
    if (exception.name === 'NotFoundException') {
      return '请求资源不存在'
    }
    if (exception.name === 'HttpException') {
      let errorResp = exception.getResponse() as Record<string, any>
      return Object.values(errorResp.message).join(',')
    }
    if (exception.name === 'Error') {
      return exception.message
    }
    return '请求错误'
  }
}
